
import numpy as np
from matplotlib import pyplot as plt

from collections import Counter
from 视图分离 import get_clusters
# 指定要读取的DXF文件路径


def find_most_frequent_x_and_y(points):
    # 提取所有 x 值和 y 值
    x_values = [point[0] for point in points]
    y_values = [point[1] for point in points]
 
    # 统计 x 和 y 的频率
    x_counter = Counter(x_values)
    y_counter = Counter(y_values)
 
    # 找到出现次数最多的 x 和 y
    most_frequent_x = x_counter.most_common(1)[0][0]
    most_frequent_y = y_counter.most_common(1)[0][0]
 
    return (most_frequent_x, most_frequent_y)
def  get_adjusted_clusters(clusters) :
    center_point = find_most_frequent_x_and_y([[round(cluster.min_x,1),round(cluster.min_y,1)] for cluster in clusters])

    范围=0.5
    adjusted_clusters = []
    def is_close(a, b, tolerance=0.2):
        return abs(a - b) <= tolerance
    
    # 提取所有 lengthx 的值，并去重（考虑正负 0.2 的范围）
    lengths = []
    for cluster in clusters:
        for  lengthx in [cluster.lengthx,cluster.lengthy]:
        # 检查当前 lengthx 是否已经存在于 lengths 中（考虑正负 0.2 的范围）
         if not any(is_close(lengthx, existing) for existing in lengths):
            lengths.append(lengthx)
            

    print(lengths)
    
    xy上下面线段集 = []
    xz左右面线段集 = []
    yz中间面线段集 = [] 
    
    for i,cluster in  enumerate(clusters) :
        adjusted_cluster = []
        lines=cluster.lines
        print(f"第{i}个聚落有{len(lines)}条线")
        lengthx=cluster.lengthx
        lengthy=cluster.lengthy
        lengthz = next((l for l in lengths if abs(l - lengthx)>0.3 and abs(l - lengthy)>0.3), lengthx)
        min_x, min_y = cluster.min_x,cluster.min_y
        print(lengthx,lengthy,lengthz)
        投影方向 = ''
        投影矩阵 = {
            "左边投影": np.array([
                [-1, 0, lengthx + min_x],
                [0, 0, lengthz],
                [0, 1, -min_y]
            ]),
            "下边投影": np.array([
                [0, -1, lengthy + min_y],
                [1, 0, -min_x],
                [0, 0, lengthz]
            ]),
            "中间投影": np.array([
                [0, 0,lengthz],
                [1, 0, -min_x],
                [0, 1, -min_y]
            ]),
            "右边投影": np.array([
                [1, 0, - min_x],
                [0, 0, 0],
                [0, 1, -min_y]
            ]),
            "上边投影": np.array([
                [0, 1, - min_y],
                [1, 0, -min_x],
                [0, 0, 0]
            ]),
        }
        if min_x - center_point[0]<-范围 :
            投影方向 = "左边投影"   
        elif min_y- center_point[1]<-范围 :
            投影方向 = "下边投影"
        elif abs(min_y - center_point[1])<范围 and abs(min_x - center_point[0])<范围:
            投影方向 = "中间投影"
        elif min_x - center_point[0]>范围 :
            投影方向 = "右边投影"    
        elif min_y- center_point[1]>范围 :
            投影方向 = "上边投影"
        for line in lines:
                
                adjusted_line = [
                    np.round(投影矩阵[投影方向].dot(np.array([p[0], p[1], 1]) ),1)
                    for p in line
                ]
                adjusted_cluster.append(adjusted_line)
                if 投影方向 == '中间投影':
        
                    yz中间面线段集.append( adjusted_line) 
                
                elif 投影方向 == '下边投影' or 投影方向 == '上边投影':
                
                    xy上下面线段集.append( adjusted_line)
                
                elif 投影方向 == '左边投影' or 投影方向 == '右边投影':
                
                    xz左右面线段集.append( adjusted_line)
        adjusted_clusters.append(adjusted_cluster)
        print(f'{投影方向},视图编号:{i}')
 
    return adjusted_clusters,yz中间面线段集,xy上下面线段集,xz左右面线段集   
        
        
        
if __name__ == "__main__": 
 
    
    dxf_file_path = 'a.dxf'
    
    clusters=get_clusters(dxf_file_path)
    adjusted_clusters=get_adjusted_clusters(clusters)[0]
    # 创建一个3D图形
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    colors = plt.cm.tab20.colors
    # 遍历 adjusted_clusters 中的每个簇
    for i, cluster in enumerate(adjusted_clusters):
        color = colors[i % len(colors)]
        for line in cluster:
            # 将每个线的点拆分为 x, y, z 坐标
            x = [p[0] for p in line]
            y = [p[1] for p in line]
            z = [p[2] for p in line]
            
            # 绘制线
            ax.plot(x, y, z,color=color)
    
    # 设置坐标轴标签
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    ax.set_aspect('equal')
    # 显示图形
    plt.show()